package com.fog.student.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fog.student.common.UserContext;
import com.fog.student.dto.ClassDto;
import com.fog.student.dto.SelectedCourseDto;
import com.fog.student.entity.*;
import com.fog.student.entity.Class;
import com.fog.student.mapper.ClassMapper;
import com.fog.student.service.ClassService;
import com.fog.student.service.StudentService;
import com.fog.student.service.TeacherService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ClassServiceImpl extends ServiceImpl<ClassMapper,Class> implements ClassService {
    @Resource
    private ClassService classService;

    @Resource
    private StudentService studentService;

    @Resource
    private TeacherService teacherService;


    @Override
    public Page<ClassDto> selectTeacherClass(int page, int pageSize, String name) {
        Page<Class> pageInfo = new Page<>(page, pageSize);

        Page<ClassDto> classDtoPage = new Page<>();

        QueryWrapper<Class> classQueryWrapper = new QueryWrapper<>();

        classQueryWrapper.orderByDesc("id");

        if(name!=null){
            classQueryWrapper.like("name",name);
        }
        int classId = teacherService.getById(UserContext.getUserId().toString()).getClassId();
        classQueryWrapper.eq("id",classId);

        // 查出信息
        page(pageInfo, classQueryWrapper);
        // 拷贝信息
        BeanUtils.copyProperties(pageInfo, classDtoPage);

        List<Class> records = pageInfo.getRecords();

        List<ClassDto> recordsDto = records.stream().map((item)->{
            ClassDto classDto = new ClassDto();
            BeanUtils.copyProperties(item, classDto);
            int studentNum = getStudentNum(item.getId());
            classDto.setStudentNum(studentNum);
            return classDto;
        }).collect(Collectors.toList());

        classDtoPage.setRecords(recordsDto);

        return classDtoPage;
    }

    @Override
    public int getStudentNum(int classId) {
        QueryWrapper<Student> studentQueryWrapper = new QueryWrapper<>();

        studentQueryWrapper.eq("class_id",classId);

        return studentService.count(studentQueryWrapper);
    }
}
